<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="创建时间">
                <a-range-picker
                  show-time
                  v-model="queryParam.buildTime"
                  style="width: 100%"
                  :placeholder="['请选择开始日期', '请选择结束日期']"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24" v-if="isTiming == 1">
              <a-form-item label="定时时间">
                <a-range-picker
                  show-time
                  v-model="queryParam.timingBuildTime"
                  style="width: 100%"
                  :placeholder="['请选择开始日期', '请选择结束日期']"
                />
              </a-form-item>
            </a-col>
            
            <a-col :md="8" :sm="24">
              <a-form-item label="发送区域">
                <a-select v-model="queryParam.status" placeholder="请选择发送区域">
                  <a-select-option v-for="it in isOverseaList" :key="it.id" :value="it.id">{{ it.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam.status" placeholder="请选择状态">
                  <a-select-option v-for="it in statusList" :key="it.id" :value="it.id">{{ it.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="产品">
                <AWM-select
                  v-model="queryParam.productId"
                  placeholder="请选择产品"
                  funStr="productByNoAuth"
                ></AWM-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => ((this.queryParam = {}), (this.need = {}))"
                  >重置</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="c_columns"
        :data="loadData"
        showPagination="auto"
        :scroll="{ x: 'auto' }"
      >
        <span slot="receive" slot-scope="text">
          <ul>
            <li v-for="(it, i) in text.slice(0, 2)" :key="it + '' + i"><a-badge status="default" :text="it" /></li>
          </ul>
          <a @click="handleMore(text)" v-if="text.length > 2">查看更多</a>
        </span>
        <span slot="details" slot-scope="text, record">
          <span class="default-wrap">总数: {{ record.receiveNum + record.curtailReceiveNum }}</span
          >&nbsp;&nbsp;
          <span class="success-wrap">成功: {{ record.successNum }}</span
          >&nbsp;&nbsp; <span class="default-wrap">未知: {{ record.unknownNum }}</span
          >&nbsp;&nbsp;
          <br/>
          <span class="danger-wrap">失败: {{ record.failureNum }}</span>&nbsp;&nbsp;
          <span class="danger-wrap">未提交: {{ record.unSubmitNumber }}</span>
        </span>
        <span slot="param" slot-scope="text">
          <div class="param-wrap">{{ text }}</div>
        </span>
        <span slot="ftype" slot-scope="text, record">
          {{ record.typeId1Name }}{{ record.typeId2Name ? ` - ${record.typeId2Name}` : '' }}
        </span>

        <span slot="status" slot-scope="text">
          <a-tag :color="text | statusFilter(statusList, 'status')">{{
            text | statusFilter(statusList, 'name')
          }}</a-tag>
        </span>
        <span slot="amount" slot-scope="text">￥{{ text | NumberFormat }}</span>
        <span slot="action" slot-scope="text, record">
          <span>
            <a @click="handleLook(record)">查看回执</a>
            <a-divider type="vertical" />
            <a @click="handleUnknow(record)">未提交号码</a>
          </span>
        </span>
        <span slot="remark" slot-scope="text">
          <template>
            <div class="remark-wrap">{{ text }}</div>
          </template>
        </span>
        <!-- <span slot="action" slot-scope="text, record">
          <span>
            <a @click="handleLook(record)">查看回执</a>
            <a-divider type="vertical" />
            <a @click="handleUnknow(record)">未提交号码</a>
          </span>
        </span> -->
      </s-table>
      <a-descriptions style="margin-top: 10px; width: 300px" :column="2" size="small">
        <a-descriptions-item label="总数">
          {{ (sum.success + sum.failure + sum.unknown) | NumberFormat }}
          <!-- {{ (sum.curtailReceiveNum + sum.receiveNum) | NumberFormat }} -->
        </a-descriptions-item>
        <a-descriptions-item label="成功数"> {{ sum.success | NumberFormat }} </a-descriptions-item>
        <a-descriptions-item label="发送金额"> ￥{{ sum.sendAmount | NumberFormat }} </a-descriptions-item>
        <a-descriptions-item label="失败数"> {{ sum.failure | NumberFormat }} </a-descriptions-item>
        <a-descriptions-item label="到达率"> {{ sum | msgArrive | NumberFormat }} %</a-descriptions-item>
        <a-descriptions-item label="未知数"> {{ sum.unknown | NumberFormat }} </a-descriptions-item>
      </a-descriptions>
    </a-card>
    <more-phone :visible="more.visible" :list="more.list" @ok="handleMoreOk" @cancel="handleMoreOk"></more-phone>
    <MSG-list :visible="look.visible" :data="look.mdl" @cancel="handleLookCancel"></MSG-list>
    <unkonw-MSG-list :visible="unknow.visible" :data="unknow.list" @cancel="handleUnknowCancel"></unkonw-MSG-list>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { msgLogList } from '@/api/sms'
import { msgStatusList, isOverseaList } from '@/utils/other'
import { mapGetters } from 'vuex'
import MSGList from './mouduls/MSGList'
import AWMSelect from '@/components/AWMSelect'
import MorePhone from '@/components/MorePhone'
import UnkonwMSGList from './mouduls/UnkonwMSGList'

const columns = [
  {
    title: '手机号码',
    dataIndex: 'receive',
    width: 180,
    scopedSlots: { customRender: 'receive' },
  },

  {
    title: '内容',
    width: '230px',
    dataIndex: 'content',
  },
  // {
  //   title: '使用场景',
  //   width: '200px',
  //   dataIndex: 'remark',
  //   customRender: (text) => text || '--',
  //   // scopedSlots: { customRender: 'need' },
  // },
  {
    title: '产品名称',
    dataIndex: 'productName',
    width: '150px',
  },

  {
    title: '添加时间',
    dataIndex: 'addTime',
    width: '180px',
  },
  {
    title: '定时发送',
    dataIndex: 'timing',
    width: '180px',
    customRender: (text) => text || '--',
  },
  {
    title: '发送详情',
    dataIndex: 'details',
    width: '230px',
    scopedSlots: { customRender: 'details' },
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: '200px',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 180,
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'log-list',
  components: {
    STable,
    MSGList,
    AWMSelect,
    MorePhone,
    UnkonwMSGList
  },
  data() {
    this.columns = columns
    return {
      more: {
        visible: false,
        list: [],
      },
      open: false,
      need: {},
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParam: {},
      look: {
        visible: false,
        mdl: {},
      },
      data: [],
      sum: {
        unknown: 0,
        success: 0,
        failure: 0,
        sendAmount: 0,
        platformAmount: 0,
      },
      unknow:{
        visible: false,
        list: []
      },
      // 状态
      statusList: msgStatusList,
      isOverseaList,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        // 附加属性
        let subParam = {}
        const requestParameters = Object.assign({}, parameter, this.queryParam, {timing: 1})
        // requestParameters.addUser = this.$store.getters.userInfo.id || 0
        requestParameters.buildTime
        if (requestParameters.buildTime) {
          requestParameters.endTime = requestParameters.buildTime[1] || ''
          requestParameters.startTime = requestParameters.buildTime[0] || ''
          delete requestParameters.buildTime
        }
        if (requestParameters.timingBuildTime) {
          requestParameters.timingEndTime = requestParameters.timingBuildTime[1] || ''
          requestParameters.timingStartTime = requestParameters.timingBuildTime[0] || ''
          delete requestParameters.timingBuildTime
        }

        return msgLogList(requestParameters).then((res) => {
          if (parameter.pageNo == 1 ) {
            if(res.data.data.length){
              this.sum = {
                unknown: res.data.data[0].unknown || 0,
                success: res.data.data[0].success || 0,
                failure: res.data.data[0].failure || 0,
                sendAmount: res.data.data[0].sendAmount || 0,
                platformAmount: res.data.data[0].platformAmount || 0,
              }
            }else{
              this.sum = {
                unknown: 0,
                success: 0,
                failure: 0,
                sendAmount: 0,
                platformAmount: 0,
              }
            }
          }
          let result = {
            data: res.data.data.map((v) => {
              let paramReceive = JSON.parse(v.paramReceive) || ['']
              let overfrequency = []
              v.resExts ? (v.resExts = JSON.parse(v.resExts),overfrequency = v.resExts.overfrequency || []):null
              v.receive = paramReceive
              v.overfrequency = overfrequency.map(v=>{ return { phone: v}})
              return v
            }),
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created() {},
  computed: {
    ...mapGetters({ baseUrl: 'baseUrl', userInfo: 'userInfo' }),
    // isTiming: function () {
    //   console.log(this.$route.path.indexOf('/timing'))
    //   return this.$route.path.indexOf('/timing') != -1
    // },
    isTiming: function () {
      return 1
    },

    computedQueryParam: function () {
      return {
        timing: this.isTiming,
      }
    },
    c_columns:function(){
      let { isTiming, columns} = this
      console.log(isTiming, columns);
      if(!isTiming){
        return columns.filter(v=>v.dataIndex != 'timing')
      }else{
        return columns
      }
    }
  },
  methods: {
    
    handleUnknow(record){
      this.unknow.visible = true
      this.unknow.list = record.overfrequency || []
    },
    handleUnknowCancel() {
      this.unknow.visible = false
      setTimeout(()=>{
        this.unknow.list = []
      }, 500)
    },
    handleLook(record) {
      this.look.visible = true
      this.look.mdl = { ...record }
    },
    handleLookCancel() {
      this.look.visible = false
      this.look.mdl = {}
    },
    handleCheckList(record) {
      this.check.mdl = { ...record }
      this.check.visible = true
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },

    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleMore(a_data) {
      this.more.visible = true
      this.more.list = a_data
    },
    handleMoreOk() {
      this.more.visible = false
      this.more.list = []
    },
  },
  filters: {
    msgArrive: function (obj) {
      let { success=0, failure=0, unknown=0 } = obj
      let sum = success + failure + unknown
      console.log((((success || 0)/ sum )*100).toFixed(1));
      return parseFloat((((success || 0)/ sum )*100).toFixed(1))
    },
  },
}
</script>
<style scoped lang="less">
.param-wrap {
  min-width: 200px;
  max-width: 300px;
}

.a-tag-wrap {
  font-size: 12px;
  /deep/ .ant-tag {
    line-height: 18px;
    padding: 0 4px;
  }
  div {
    margin-bottom: 2px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.success-wrap {
  color: #14d36a;
  font-size: 12px;
}
.default-wrap {
  color: #999;
  font-size: 12px;
}
.danger-wrap {
  color: #fc0119;
  font-size: 12px;
}
</style>

 